<template>
  <div class="edit">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :default-config="toolbarConfig"
      :editor="editorRef"
    />
    <Editor
      style="height: 320px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { baseURL } from "../config/axios.config";
import { getLoggedUser } from "../utils/stateUtils";

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const valueHtml = ref("");
const toolbarConfig = {
  excludeKeys: [
    "group-video", // 排除菜单组，写菜单组 key 的值即可
  ],
};
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: `${baseURL}/post/upload`,
      fieldName: "file",
      // 自定义增加 http  header
      headers: {
        token: getLoggedUser().token,
      },
    },
  },
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
defineExpose({
  getHtml: () => editorRef.value.getHtml(),
  getText: () => editorRef.value.getText(),
  setHtml: (html) => editorRef.value.setHtml(html),
  clear: () => editorRef.value.clear(),
});
</script>

<style scoped>
.edit {
  border: 1px solid #ccc;
  width: 800px;
}
</style>
